package edu.whut.mall.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.whut.mall.common.util.Md5Util;
import edu.whut.mall.pojo.mapper.UserMapper;
import edu.whut.mall.pojo.model.User;
import edu.whut.mall.user.dto.UserDto;
import edu.whut.mall.user.service.IUserService;
import edu.whut.mall.user.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author smq
 * @Date 2021/8/17 20:29
 * @Uint d9lab
 * @Description:
 */
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserVo register(UserDto user) {
        Assert.notNull(user, "Parameter user can not be null!");

        Assert.hasLength(user.getUsername(), "用户名不能为空!");
        Assert.hasLength(user.getPassword(), "密码不能为空!");
        User check = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        Assert.isNull(check, "用户名已经存在!");
        User po = new User();
        BeanUtils.copyProperties(user, po);

        if (StringUtils.isBlank(po.getName())) {
            po.setName(user.getUsername());
        }
        po.setPassword(Md5Util.encrypt(user.getPassword()));
        po.setStatus(true);
        po.setCreateTime(new Date());
        userMapper.insert(po);
        User res = userMapper.selectById(po.getId());
        return UserVo.builder()
                .username(res.getUsername())
                .address(res.getAddress())
                .createTime(res.getCreateTime())
                .email(res.getEmail())
                .phone(res.getPhone())
                .build();
    }

    @Override
    public UserVo getByEmail(String email) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, email);
        User user = userMapper.selectOne(queryWrapper);
        return user == null ? null : UserVo.builder()
                .address(user.getAddress())
                .email(user.getEmail())
                .phone(user.getPhone())
                .createTime(user.getCreateTime())
                .build();
    }
}
